//
//  ViewController.swift
//  weather2
//
//  Created by HFY on 2020/9/10.
//  Copyright © 2020 mingliang. All rights reserved.
//

import UIKit
import CoreLocation
import Alamofire
import SwiftyJSON

class ViewController: UIViewController {
    
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var cityLabel: UILabel!
    @IBOutlet weak var tempLabel: UILabel!
    let locationManager = CLLocationManager()
    let weather = Weather()
    let appid = "1ad46c7e87981c09eb1e4dd157a8db9a"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
        locationManager.requestLocation()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        locationManager.requestWhenInUseAuthorization()
        
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let lat = locations[0].coordinate.latitude
        let lon = locations[0].coordinate.longitude
        print(lat,lon)
        let paras = ["lat":"\(lat)","lon":"\(lon)","appid":appid]
        getWeather(paras: paras)
    
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
        
        // as 向上转型f
        // as? 向下转型
        // as! 向下转型
        let vc = segue.destination as! SelcetCityController
        vc.currentCity = weather.city
        
        vc.delegate = self
    }
    
}


extension ViewController:CLLocationManagerDelegate,SelectCityDelegate{
    
    func didChangeCity(city: String) {
        let paras = ["q":city,"appid":appid]
        getWeather(paras: paras)
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error)
    }
    
    func getWeather(paras:[String:String]){
        AF.request("https://api.openweathermap.org/data/2.5/weather",parameters: paras).responseJSON { response in //回调函数，里面都要用 self
        
            if let json = response.value {
                let weather = JSON(json)
                
                self.createWeather(weatherJSON: weather)
                
                self.updateUI()
                
        }
            
        }
    }
    
    func createWeather(weatherJSON:JSON){
        weather.city = weatherJSON["name"].stringValue
        weather.temp = Int(round(weatherJSON["main","temp"].doubleValue-273.15))
        weather.condition = weatherJSON["weather",0,"id"].intValue
    }
    
    func updateUI(){
        cityLabel.text = weather.city
        tempLabel.text = "\(weather.temp)°"
        imageView.image = UIImage(named: weather.icon)
    }
}
